<?php declare(strict_types=1);

$di = \application\units\Di::getInstance();

$params = [
    'pid' => $di->request->params('pid'),
    'id'  => $di->request->params('id'),
];

$resourceIds = array_column($di->db->query('select resource_id from admin_role_resource_access where role_id in (:role_id)', [
    'role_id' => $params['pid'],
]), 'resource_id');

$selectResourceIds = [];

if ($params['id'] > 0) {
    $selectResourceIds = array_column($di->db->query('select resource_id from admin_role_resource_access where role_id in (:role_id)', [
        'role_id' => $params['id'],
    ]), 'resource_id');
}


if (in_array(0, $resourceIds)) {
    $rows = $di->db->query('select * from admin_resource');
} else {
    $rows = $di->db->query('select * from admin_resource where id in (:id)', [
        'id' => $resourceIds,
    ]);
}

$ids  = array_column($rows, 'id');
$pids = array_column($rows, 'pid');

foreach ($rows as &$row) {
    if (!in_array($row['pid'], $ids)) {
        $row['pid'] = 0;
    }
    if (!in_array($row['id'], $pids)) {
        $row['selected'] = in_array($row['id'], $selectResourceIds);
    }
}


return [
    'total' => count($rows),
    'rows'  => $rows,
];